﻿#region << 文件说明 >>

/*----------------------------------------------------------------
 * 命名空间：Vampirewal.BlogCore.Extension
 * 唯一标识：c962cc3b-ac4b-4416-b940-d6bbb2474843
 * 文件名：BlogOptionsExtension
 *
 * 创建者：杨程
 * 电子邮箱：235160615@qq.com
 * 创建时间：2024/6/28 14:39:28
 * 版本：V1.0.0
 * 描述：
 *
 * ----------------------------------------------------------------
 * 修改人：
 * 时间：
 * 修改说明：
 *
 * 版本：V1.0.1
 *----------------------------------------------------------------*/

#endregion << 文件说明 >>

using System.IO;

namespace Vampirewal.BlogCore;

/// <summary>
/// 配置扩展方法
/// </summary>
public static class BlogOptionsExtension
{
    /// <summary>
    /// 获取配置的具体类
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <param name="option"></param>
    /// <returns></returns>
    public static T GetValue<T>(this IBlogOption<T> option) where T : class, new()
    {
        if (option == null)
        {
            T t = new T();
            return t;
        }

        return (option as T)!;
    }

    /// <summary>
    /// 处理获取对象异常问题
    /// </summary>
    /// <typeparam name="T">类型</typeparam>
    /// <param name="action">获取对象委托</param>
    /// <param name="defaultValue">默认值</param>
    /// <returns>T</returns>
    private static T CatchOrDefault<T>(Func<T> action, T defaultValue = null)
        where T : class
    {
        try
        {
            return action();
        }
        catch
        {
            return defaultValue ?? null;
        }
    }

    public static IServiceCollection AddBlogOptions<TOption>(this IServiceCollection services)where TOption:class,IBlogOption<TOption>
    {
        var type=typeof(TOption);

        string path = $"{type.Name.Replace("Options", "")}";

        var configurationRoot = App.Configuration;
        //var optionsConfiguration = configurationRoot.GetSection(path);

        //var optionsConfigure = services.AddOptions<TOption>()
        //      .Bind(optionsConfiguration, options =>
        //      {
        //          options.BindNonPublicProperties = true; // 绑定私有变量
        //      })
        //      .ValidateDataAnnotations();

        var op= Activator.CreateInstance(type);

        services.AddSingleton(typeof(IBlogOption<>).MakeGenericType(type), op);

        configurationRoot.Bind(op);

        return services;
    }
}